#pragma strict

var elevator_speed:float;

private var moving_direction:int; // -1 descendo, 0 parado, 1 andando
private var curr_floor:int;
private var next_floor:int;

function Start () {
	moving_direction = 0;
}

function Update () {
	var player_obj:GameObject = SceneManager.Instance().GetPlayer();
	if (!SceneManager.Instance().IsGameOver()) {
		if (moving_direction != 0) {	
			if (Arrived()) {
				if ((!Input.GetButton("Up") && !Input.GetButton("Down"))) {
					audio.Stop();
				}
				moving_direction = 0;
				curr_floor = next_floor;
				SceneManager.Instance().EnablePlayerInput();
				player_obj.rigidbody.velocity.y = 0;
				rigidbody.velocity.y = 0;
			}
			else {
				player_obj.rigidbody.velocity.y = elevator_speed * moving_direction;
				rigidbody.velocity.y = elevator_speed * moving_direction;
			}
		}
		else {
			if (IsPlayerInside()) {
				if (Input.GetButton("Up")) {		
					if (curr_floor + 1 < SceneManager.Instance().max_floors) {
						moving_direction = 1;
						if (!audio.isPlaying && !SceneManager.Instance().mute) audio.Play();
						SceneManager.Instance().DisablePlayerInput();
						player_obj.rigidbody.velocity.x = 0;
						next_floor = curr_floor + 1;
					}
				}
				else if (Input.GetButton("Down")) {		
					if (curr_floor > 0) {
						moving_direction = -1;
						if (!audio.isPlaying && !SceneManager.Instance().mute) audio.Play();
						SceneManager.Instance().DisablePlayerInput();
						player_obj.rigidbody.velocity.x = 0;
						next_floor = curr_floor - 1;
					}
				}
			}		
		}
		if (SceneManager.Instance().mute) audio.Stop();
	}	
	else {
		rigidbody.velocity.y = 0;
		player_obj.rigidbody.velocity.y = 0;
	}
}

function IsPlayerInside() : boolean {
	var player_obj:GameObject = SceneManager.Instance().GetPlayer();
	var player_left_bound:float = player_obj.transform.position.x - (player_obj.collider.bounds.size.x / 2);
	var elevator_left_bound:float = transform.position.x - (collider.bounds.size.x / 2);
	if (player_left_bound > elevator_left_bound) return true;
	else {
		return false;
	}
}

function Arrived(): boolean {
	if (moving_direction > 0) {
		if (transform.position.y >= GetFloorPosition(next_floor).y) {
			transform.position.y = GetFloorPosition(next_floor).y;
			return true;
		}
	} 
	else if (moving_direction < 0) {
		if (transform.position.y <= GetFloorPosition(next_floor).y) {
			transform.position.y = GetFloorPosition(next_floor).y;
			return true;
		}
	} 
	else return false;
}

function GetFloorPosition(floor: int) : Vector3 {
	return Vector3(0, collider.bounds.size.y * (floor + 1) - (collider.bounds.size.y / 2), 0);
}